package com.dudu.controller;

import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.mortbay.log.Log;

import com.dudu.bean.AppExtendBean;
import com.dudu.enumeration.OperateTypeEnum;
import com.dudu.service.IAppExtendService;
import com.dudu.service.ILogService;
import com.dudu.service.impl.AppExtendServiceImpl;
import com.dudu.service.impl.LogService;
import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.EnumUtility;
import com.dudu.utils.MD5Utils;

import core.CoreService;

/**
 * 根据AppKey查询信息实现类
 * 
 * @author 唐建
 * @date 2016-7-11
 */
public class OpenOperateByAppKeyController extends CoreService implements IOpenOperateByAppKeyController {

    // 用于记录相应接口调用的日志
    private ILogService logService = new LogService();
    // app扩展信息操作
    private IAppExtendService appExtendService = new AppExtendServiceImpl();
    // 对外返回参数
    private JSONObject object = new JSONObject();
    // 3.0 地址
    private String url = DictionaryUtils.getValueByTypeAndKey("url", "dudu3.0");
    // 运营平台鉴权接口
    private String url_authentication = DictionaryUtils.getValueByTypeAndKey("platform", "verifyProductAccount");
    // 话单推送地址
    private String url_ticket = DictionaryUtils.getValueByTypeAndKey("platform", "importCallMessage");
    // 状态推送
    private String url_callstatus = DictionaryUtils.getValueByTypeAndKey("status", "import");
    private String url_ivrdigit = "";
    private String url_notice = "";
    private String url_record = "";
    private String url_sms = "";

    /**
     * 根据appkey查询信息
     * 
     * @param appkey
     *            应用标示
     * 
     * */
    @Override
    public String qryByAppKey() {
	Log.info("load OpenIOpenQuery.qryByAppKey 根据AppKey查询相关信息");
	// 获取appkey参数
	String appkey = this.getRequest().getParameter("appkey");
	String timestamp = "";
	// 获取验证码参数
	String sign = "";
	double begin = Calendar.getInstance().getTimeInMillis();
	// 首先查询v4版本数据是否存在
	try {
	    appExtendService.qryVersionFour(object, appkey, timestamp, sign);
	    if (!(object.get("result").equals("0"))) {
		// 查询v3版本是否存在
		if (object.get("code").equals("0002")) {
		    object = appExtendService.qryVersionThree(url, appkey, timestamp, sign);

		}
	    }
	} catch (Exception e) {
	    log.info("********查询失败**********");
	    object.put("result", "-1");
	    object.put("describe", "错误" + e.getMessage());

	}
	// 拼凑字符串
	String request_msg = "app_key:" + appkey + "|timestamp:" + timestamp + "|sign:" + sign;
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	this.logService.logInterface(during, "qryByAppKey", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), this.getRequest()
		.getRemoteAddr(), null);
	log.info(request_msg);
	return returnData(object.toString());
    }

    /**
     * 根据appkey更新信息
     * 
     * @param appkey
     *            应用标示
     * @param timestamp
     *            时间戳
     * @param sign
     *            验证码
     * @param urlcallstatus
     *            会议推送状态地址
     * @param urlticket
     *            话单推送地址
     * @param urlivrdigit
     *            ivr按键结果推送地址
     * @param urlrecord
     *            录音文件推送地址
     * @param linker_phone
     *            联系人
     * */
    @Override
    public String updByAppKey() {
	Log.info("load OpenOperateByApp.updByAppKey 根据AppKey更新相关信息");
	double begin = Calendar.getInstance().getTimeInMillis();
	// 获取appkey参数
	String appkey = this.getRequest().getParameter("appkey");
	// 获取timestamp参数
	String timestamp = this.getRequest().getParameter("timestamp");
	// 获取验证码参数
	String sign = this.getRequest().getParameter("sign");
	// 获取会议状态推送地址
	String urlcallstatus = this.getRequest().getParameter("urlcallstatus");
	// 获取话单推送地址
	String urlticket = this.getRequest().getParameter("urlticket");
	// IVR按键结果推送地址
	String urlivrdigit = this.getRequest().getParameter("urlivrdigit");
	// 录音文件推送地址
	String urlrecord = this.getRequest().getParameter("urlrecord");
	String linker_phone = this.getRequest().getParameter("linker_phone");
	AppExtendBean qryResult = new AppExtendBean();
	try {
	    qryResult = appExtendService.qryVersionFour(object, appkey, timestamp, sign);
	    if (!(object.get("result").equals("0"))) {
		// 查询v3版本信息
		if (object.get("code").equals("0002")) {
		    object = appExtendService.qryVersionThree(url, appkey, timestamp, sign);
		    if (object.get("result").equals("0")) {
			// 查询到则更新版本3数据库
			object.put("privateKey", MD5Utils.getMd5Value());
			object.put("urlcallstatus", urlcallstatus);
			object.put("urlticket", urlticket);
			object.put("urlivrdigit", urlivrdigit);
			object.put("urlrecord", "");
			object.put("linker_phone", linker_phone);
			object = appExtendService.updVersionThree(object, url, appkey, timestamp, sign);
		    }
		}

	    } else {
		// 在版本4中查询到则验证sign
		if (appExtendService.checkSign(object, appkey, timestamp, sign, qryResult)) {
		    // 设置更新值
		    object.clear();
		    if (StringUtils.isNotBlank(urlcallstatus)) {
			qryResult.setUrl_callstatus(urlcallstatus);
		    }
		    if (StringUtils.isNotBlank(urlticket)) {
			qryResult.setUrl_ticket(urlticket);
		    }
		    if (StringUtils.isNotBlank(urlivrdigit)) {
			qryResult.setUrl_ivrdigit(urlivrdigit);
		    }
		    if (StringUtils.isNotBlank(linker_phone)) {
			qryResult.setLinker_phone(linker_phone);
		    }
		    if (StringUtils.isBlank(qryResult.getLinker_email())) {
			qryResult.setLinker_email("");
		    }
		    qryResult.setKey_private(EnumUtility.trimNumm(MD5Utils.getMd5Value()));
		    appExtendService.updateAppExtend(qryResult);
		    object.put("result", "0");
		    object.put("privateKey", qryResult.getKey_private());
		    object.put("publicKey", qryResult.getKey_public());
		    object.put("urlcallstatus", qryResult.getUrl_callstatus());
		    object.put("urlticket", qryResult.getUrl_ticket());
		    object.put("urlivrdigit", qryResult.getUrl_ivrdigit());
		    object.put("urlrecord", qryResult.getUrl_record());
		    logService.log(OperateTypeEnum.EDIT.getKey(), 12, "公司运营", "t_app_extend", "对应用标识为:" + qryResult.getApp_key() + "通过appkey更新应用部分信息");
		    return returnData(object.toString());
		}
	    }
	} catch (Exception e) {
	    log.info("********更新失败**********");
	    object.clear();
	    object.put("result", "-1");
	    object.put("describe", "错误");
	}
	// 拼凑字符串
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "appkey:" + appkey + "|timestamp:" + timestamp + "|sign:" + sign;
	this.logService.logInterface(during, "updByAppKey", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), this.getRequest()
		.getRemoteAddr(), null);
	return returnData(object.toString());
    }

    /**
     * app扩展信息表新增数据接口， 供运营平台使用， 在运营平台创建APP信息时在 能力平台4.0环境同步 创建APP扩展信息
     * 
     * @param app_key
     *            应用标识 必要
     * @param periphery_code
     *            系统编码 必要
     * @param key_public
     *            永久秘钥 自动生成
     * @param key_private
     *            临时秘钥 自动生成
     * @param linker_name
     *            联系人 非必要----
     * @param linker_phone
     *            联系人电话 非必要---
     * @param linker_email
     *            联系人邮箱 非必要---
     * @param is_init_url
     *            空则默认---
     * @param is_init_validate
     *            空则默认---
     * @param url_ticket
     *            空则默认，非空追加
     * @param url_callstatus
     *            空则默认，非空追加
     * @param url_authentication
     *            空则默认，非空追加
     * @param url_ivrdigit
     *            空则默认，非空追加
     * @param url_notice
     *            空则默认，非空追加
     * @param url_sms
     *            空则默认，非空追加
     * @param url_record
     *            空则默认，非空追加
     * @param billing_platform
     *            空则默认，非空追加---
     * @param create_time
     *            自动生成
     * @param create_user
     *            空则默认，非空追加---
     * 
     * @author Tears 2016.7.15
     */
    @Override
    public String addInfoByAppKey() {
	Log.info("load OpenOperateByApp.addInfoByAppKey 根据AppKey新增相关信息");
	double begin = Calendar.getInstance().getTimeInMillis();
	// 先获取参数
	getParams();
	JSONObject qryresult = new JSONObject();
	// String app_key= this.getRequest().getParameter("app_key");
	// app_key与periphery_code是否为空
	try {
	    if (!(StringUtils.isBlank(object.getString("app_key")) || StringUtils.isBlank(object.getString("periphery_code")))) {
		// 根据appkey查询是否已经存在
		// 查询版本4
		appExtendService.qryVersionFour(qryresult, object.get("app_key").toString(), "", "");
		if (!qryresult.get("result").equals("0")) {
		    // 如果没有则插入
		    AppExtendBean appExtendBean = JsonTOBean();
		    int insertResult = appExtendService.insertAppExtend(appExtendBean);
		    if (insertResult != -1) {
			object.put("result", "0");
			object.remove("describe");
		    } else {
			object.clear();
			object.put("result", "-1");
			object.put("code", "0004");
			object.put("des", "插入信息错误，请检查后重试");
		    }
		} else {
		    object.clear();
		    object.put("result", "-1");
		    object.put("code", "0003");
		    object.put("des", "信息已存在，无法新增");
		}

	    } else {
		object.clear();
		object.put("result", "-1");
		object.put("code", "0004");
		object.put("des", "app_key和periphery_code不能为空");
	    }
	} catch (Exception e) {
	    object.clear();
	    object.put("result", "-100");
	    object.put("code", "0000");
	    object.put("des", "exception:" + e.getMessage() + e.getStackTrace());
	}
	// 拼凑字符串
	double end = Calendar.getInstance().getTimeInMillis();
	// 时间差
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼日志内容
	String request_msg = "appkey:" + object.get("appkey") + "|timestamp:" + object.get("timestamp") + "|sign:" + object.get("sign");
	this.logService.logInterface(during, "addInfoByAppKey", request_msg, object.toString(), object.getString("result"), DateUtils.getCurrentTime(), this.getRequest()
		.getRemoteAddr(), null);
	return returnData(object.toString());
    }

    private void getParams() {
	Map pmap = this.getRequest().getParameterMap();
	Iterator<Map.Entry<String, String>> it = pmap.entrySet().iterator();
	while (it.hasNext()) {
	    Map.Entry<String, String> entry = it.next();
	    Object valobj = entry.getValue();
	    String val = "";
	    if (valobj instanceof String[]) {
		String[] vals = (String[]) valobj;
		val = vals[0];
	    } else {
		val = valobj.toString();
	    }
	    object.put(entry.getKey().toString(), val);
	}

    }

    private void checkJsonParams() {

	if (!object.containsKey("create_user")) {
	    object.put("create_user", "");
	} else {
	    object.put("create_user", "公司运营");
	}
	if (!object.containsKey("billing_platform")) {
	    object.put("billing_platform", "");
	}
	if (!object.containsKey("is_init_url")) {
	    object.put("is_init_url", "");
	}
	if (!object.containsKey("is_init_validate")) {
	    object.put("is_init_validate", "");
	}

	if (!object.containsKey("linker_email")) {
	    object.put("linker_email", "");
	}
	if (!object.containsKey("linker_name")) {
	    object.put("linker_name", "");
	}
	if (!object.containsKey("linker_phone")) {
	    object.put("linker_phone", "");
	}
	// url_callstatus
	setURLs(url_callstatus, "url_callstatus");
	// url_ivrdigit
	setURLs(url_ivrdigit, "url_ivrdigit");
	// url_notice
	setURLs(url_notice, "url_notice");
	// url_record
	setURLs(url_record, "url_record");
	// url_sms
	setURLs(url_sms, "url_sms");
	// url_ticket
	setURLs(url_ticket, "url_ticket");
    }

    private void setURLs(String url, String name) {
	if(StringUtils.isBlank(object.optString(name))){
	    object.put(name, url);
	}else if(!object.optString(name).contains(url)){
	    object.put(name, url + "," + object.get(name).toString());
	}else{
	    object.put(name, url);
	}
	
    }

    private AppExtendBean JsonTOBean() {
	checkJsonParams();
	AppExtendBean bean = new AppExtendBean();
	bean.setApp_key(object.get("app_key").toString());
	// bean.setApp_name(object.get("app_name").toString());
	bean.setCreate_time(DateUtils.getCurrentDate());
	bean.setCreate_user(object.getString("create_user"));
	if (StringUtils.isBlank(object.getString("billing_platform"))) {
	    bean.setBilling_platform("03");
	} else {
	    bean.setBilling_platform(object.getString("billing_platform"));
	}
	if (StringUtils.isBlank(object.getString("is_init_url"))) {
	    bean.setIs_init_url("0");
	} else {
	    bean.setIs_init_url(object.getString("is_init_url"));
	}
	if (StringUtils.isBlank(object.getString("is_init_validate"))) {
	    bean.setIs_init_validate("0");
	} else {
	    bean.setIs_init_validate(object.getString("is_init_validate"));
	}
	bean.setKey_private(MD5Utils.getMd5Value());
	bean.setKey_public(MD5Utils.getMd5Value());
	bean.setLinker_email(object.get("linker_email").toString());
	bean.setLinker_name(object.get("linker_name").toString());
	bean.setLinker_phone(object.get("linker_phone").toString());
	bean.setPeriphery_code(object.get("periphery_code").toString());
	// 鉴权地址不变
	bean.setUrl_authentication(url_authentication);
	bean.setUrl_callstatus(object.get("url_callstatus").toString());
	// **********************************************
	// url_ivrdigit
	bean.setUrl_ivrdigit(object.get("url_ivrdigit").toString());
	// url_notice
	bean.setUrl_notice(object.getString("url_notice"));
	// url_record
	bean.setUrl_record(object.getString("url_record"));
	// url_sms
	bean.setUrl_sms(object.getString("url_sms"));
	// url_ticket
	bean.setUrl_ticket(object.getString("url_ticket"));
	bean.setUrl_infocontrol(object.optString("url_infocontrol"));
	return bean;

    }

}
